﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.UI.WebControls;
using easyVal.ServerSide;
using easyVal.Web.Extensions;

namespace easyVal.Web
{
    public class ClientModelValidation
    {
        private readonly Type _modelType;

        public ClientModelValidation(Type type)
        {
            _modelType = type;
        }

        /// <summary>
        /// This method adds Jquery validatiion
        /// </summary>
        public void AddValidation(WebControl control, string PropertyName)
        {
            PropertyInfo propInfo = _modelType.GetProperty(PropertyName);

            if (propInfo == null)
            {
                throw new Exception(string.Format("Property {0} not found on entity {1}." , PropertyName , _modelType.Name));
            }

            IEnumerable<IClientValidationMethod> validationAttributes =
                propInfo.GetCustomAttributes(typeof (IClientValidationMethod), true).Cast<IClientValidationMethod>();

            foreach (IClientValidationMethod clientValidation in validationAttributes)
            {
                control.AddValidationAttributeEasy(clientValidation.ClientMethodName, clientValidation.ErrorMessage,
                                                   clientValidation.ClientParameters);
            }
        }
    }
}